<?php

namespace app\admin\controller;

use app\admin\logic\ExportQuestionLogic;
use app\admin\logic\ImportQuestionLogic;
use app\common\controller\Backend;
use Exception;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 课程列表(课程属于公共数据,某个专业可以自己来提取自己的课程)
 *
 * @icon fa fa-circle-o
 */
class Course extends Backend
{

    /**
     * Course模型对象
     * @var \app\admin\model\Course
     */
    protected $model = null;

    /**
     * 快速搜索时执行查找的字段
     */
    protected $searchFields = 'name';

    /**
     * selectpage搜索字段
     * @var string
     */
    protected $selectpageFields = "id,name,code";

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Course;
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $open_enhance = config('fastadmin.open_enhance');
        $this->assign('open_enhance', $open_enhance);
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $params['a_time'] = time();
                    $params['u_time'] = time();
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $params['u_time'] = time();
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 批量改价
     */
    public function editprice($ids = null)
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    // 提取参数
                    $exam_id = $params['exam_id'] ?? 0;
                    $price = $params['price'] ?? 0;

                    // 检查数据
                    if (!$exam_id) {
                        $this->error('请选择考试分类');
                    }
                    if (!is_numeric($price)) {
                        $this->error('请输入有效价格');
                    }

                    // 修改价格
                    $time = time();
                    $where = ['exam_id' => $exam_id];
                    $save_data = [
                        'exam_id' => $exam_id,
                        'price' => $price,
                        'u_time' => $time,
                    ];
                    $result = $this->model->where($where)->update($save_data);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", 1);
        return $this->view->fetch();
    }

    /**
     * 导入题目
     * @param $ids
     * @return string
     * @throws \think\Exception
     */
    public function importQuestion($ids = null)
    {
        if ($this->request->isPost()) {
            // 请求参数
            $params = $this->request->post("row/a");
            if (!$params) {
                $this->error(__('请求参数不得为空'));
            }
            if (empty($params['course_id'])) {
                $this->error(__('导入课程不得为空'));
            }
            if (empty($params['attachment'])) {
                $this->error(__('请求文件不得为空'));
            }
            // 验证extend_id必须有值
            $paper_id = $params['paper_id'] ?? 0;
            if (!$paper_id) {
                $this->error(__('请选择保存的试卷'));
            }

            try {
                Db::startTrans();
                (new ImportQuestionLogic())->import($params['course_id'], $paper_id, $params['attachment']);
                Db::commit();
            } catch (\Exception $exception) {
                Db::rollback();
                $this->error(__($exception->getMessage()));
            }
            $this->success('导入成功');
        }
        $this->assign('ids', $ids);
        return $this->view->fetch();
    }

    /**
     * 导入题目
     * @param $ids
     * @return string
     * @throws \think\Exception
     */
    public function importcatequestion($ids = null)
    {
        if ($this->request->isPost()) {
            // 请求参数
            $params = $this->request->post("row/a");
            if (!$params) {
                $this->error(__('请求参数不得为空'));
            }
            if (empty($params['course_id'])) {
                $this->error(__('导入课程不得为空'));
            }
            if (empty($params['category_id'])) {
                $this->error(__('导入分类不得为空'));
            }
            if (empty($params['attachment'])) {
                $this->error(__('请求文件不得为空'));
            }

//            Db::startTrans();
//            (new ImportQuestionLogic())->cateImport($params['course_id'], $params['category_id'], $params['attachment']);
//            Db::commit();

            try {
                Db::startTrans();
                (new ImportQuestionLogic())->cateImport($params['course_id'], $params['category_id'], $params['attachment']);
                Db::commit();
            } catch (\Exception $exception) {
                Db::rollback();
                $this->error(__($exception->getMessage()));
            }
            $this->success('导入成功');
        }
        $this->assign('ids', $ids);
        return $this->view->fetch();
    }

    /**
     * 导出题目
     * @param $ids
     * @return string
     * @throws \think\Exception
     */
    public function exportQuestion($ids = null)
    {
        if ($this->request->isPost()) {
            // 请求参数
            $params = $this->request->post("row/a");
            if (!$params) {
                $this->error(__('请求参数不得为空'));
            }
            if (empty($params['course_id'])) {
                $this->error(__('导出课程不得为空'));
            }
            try {
                $filePath = (new ExportQuestionLogic())->export([$params['course_id']], null);
            } catch (\Exception $exception) {
                var_dump($exception->getFile());
                var_dump($exception->getLine());
                $this->error(__($exception->getMessage()));
            }
            $this->success('导出成功', null, $filePath);
        }
        $this->assign('ids', $ids);
        return $this->view->fetch();
    }

}
